<template>
  <div class="Operation-box">
    <div class="btn-box">
      <el-button plain @click="addNewPoint">添加新点</el-button>
      <el-button type="primary" plain @click="() => (uploadDialog = true)"
        >导入json</el-button
      >
      <el-button type="success" plain @click="saveAsJson(tableData)"
        >导出数据</el-button
      >
    </div>
    <el-table class="table-box" :data="tableData" stripe>
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="name" label="Name" width="150">
        <template #default="scope">
          <el-input
            clearable
            v-model="scope.row.name"
            :placeholder="scope.row.name"
            @change="handlerNameChange(scope.row.name, scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="coordinate" label="Coordinate" width="350">
        <template #default="scope">
          <el-input
            clearable
            v-model="scope.row.coordinate"
            :placeholder="scope.row.coordinate"
            @change="handlerChange(scope.row.coordinate, scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="tileLayerId" label="图层ID" width="400" />
      <el-table-column prop="objectId" label="构件ID" width="150" />
      <el-table-column label="操作" fixed="right" width="200" align="center">
        <template #default="scope">
          <el-tooltip effect="dark" content="视角更新" placement="top">
            <el-button
              size="small"
              :icon="Camera"
              @click="updateCamera(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="定位" placement="top">
            <el-button
              size="small"
              :icon="Location"
              @click="location(scope.row)"
            ></el-button>
          </el-tooltip>

          <el-popconfirm title="确定?" @confirm="handlerDelete(scope.row)">
            <template #reference>
              <el-button link type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-dialog width="500" v-model="uploadDialog">
    <el-upload
      action="www.baidu.com"
      :http-request="handlerJsonUpload"
      class="upload-demo"
      multiple
      drag
      accept=".json"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        Drop file here or <em>click to upload</em>
      </div>
    </el-upload>
    <div class="code" v-if="jsonData != null">
      <h3>文件预览</h3>
      <div class="btn">
        <el-button type="primary">追加</el-button>
        <el-button type="danger">覆盖</el-button>
      </div>
      <json-viewer :value="jsonData" boxed sort />
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { UploadFilled } from "@element-plus/icons-vue";
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import { ElMessage, ElNotification } from "element-plus";
import { useCloudStore } from "@/stores/cloudStore.ts";
import {
  addMarker,
  clean,
  createPeople,
  destroyPeople,
  saveAsJson,
  updateMarker,
} from "@/views/threeView/components/funcs";
import { Camera, Location } from "@element-plus/icons-vue";
import {
  addMarkerData,
  deleteMarkerData,
  getMarkerData,
  updateMarkerData,
} from "@/api/point.ts";

const CloudStore = useCloudStore();
const uploadDialog = ref(false);
// 需要获取点
let needGetPoint = false;
// 需要更新
let needUpdate = false;
let updateObj: any = null;
const tableData = ref([]);
let jsonData: any = ref({});

const updateCamera = async (row: any) => {
  //获取相机视角
  let o = await __g.camera.get();
  await updateMarkerData(row.id, {
    camera: `[${o.camera.toString()}]`,
  });
  ElMessage({
    type: "success",
    message: "修改视角成功",
  });
  await getData();
};

const location = (row: any) => {
  __g.camera.set(JSON.parse(row.camera), 1);
};

const handlerJsonUpload = (val: any) => {
  let reader = new FileReader();
  reader.readAsText(val.file);
  reader.onload = (e: any) => {
    jsonData.value = { ...jsonData.value, ...JSON.parse(e.target.result) };
  };
};

/**
 * 获取数据
 */
const getData = async () => {
  const res: any = await getMarkerData();
  tableData.value = res;
  await addMarker(tableData.value);
};

const addNewData = async (data: any) => {
  await addMarkerData(data);
};

const handlerDelete = async (row: any) => {
  await deleteMarkerData(row.id);
  await getData();
};

onMounted(() => {
  getData();
});

watch(
  () => CloudStore.LeftClickData,
  async (newData) => {
    if (needGetPoint) {
      console.log(newData, "--newData");
      const { MouseClickPoint, camera } = newData;
      let obj;
      if (!needUpdate) {
        // 新增
        const length = tableData.value.length;
        obj = {
          name: `marker_${length}`,
          coordinate: `[${MouseClickPoint.toString()}]`,
          camera,
          tileLayerId: newData.Id,
          objectId: newData.ObjectID,
        };
        tableData.value.push(obj);
        await addNewData(obj);
      } else {
        await updateMarkerData(updateObj.id, {
          coordinate: `[${MouseClickPoint.toString()}]`,
        });
        updateObj = null;
        needUpdate = false;
      }
      await getData();
      ElNotification.closeAll();
      destroyPeople();
      needGetPoint = false;
    }
  },
  { deep: true },
);

const addNewPoint = () => {
  needGetPoint = true;
  ElNotification({
    title: "提醒",
    message: "在三维中取点,取点后自动关闭提醒",
    type: "warning",
    duration: 0,
    showClose: false,
  });
  createPeople();
};

const handlerNameChange = async (value: string | number, row: any) => {
  await updateMarkerData(row.id, {
    name: value,
  });
  await updateMarker({
    id: row.id,
    name: value,
  });
};

const handlerChange = (value: string | number, row: any) => {
  createPeople();
  const findObj = tableData.value.find((item: any) => item.name == row.name);
  if (findObj) {
    // 更新
    needUpdate = true;
    needGetPoint = true;
    ElNotification({
      title: "提醒",
      message: "在三维中取点,取点后自动关闭提醒",
      type: "warning",
      duration: 0,
      showClose: false,
    });
    updateObj = findObj;
  } else {
    if (value == "") {
      needGetPoint = true;
      ElNotification({
        title: "提醒",
        message: "在三维中取点,取点后自动关闭提醒",
        type: "warning",
        duration: 0,
        showClose: false,
      });
    } else {
      ElNotification.closeAll();
      needGetPoint = false;
    }
  }
};

onBeforeUnmount(() => {
  needGetPoint = false;
  clean();
  destroyPeople();
});
</script>

<style scoped>
.Operation-box {
  padding: 10px;
  .table-box {
    margin: 10px;
    width: calc(100% - 20px);
  }
}
.code {
  max-height: 500px;
  overflow: auto;
}
</style>
